package todo;

import se.lth.cs.realtime.semaphore.CountingSem;
import se.lth.cs.realtime.semaphore.Semaphore;
import done.ClockInput;

public class ButtonHandler extends Thread {
	private static ClockInput input;
	private static Semaphore	sem; 
	private int lastChoice;
	private SharedData sharedData;
	
	private CountingSem timeSignal;
	private CountingSem alarmSignal;

	
	public ButtonHandler(ClockInput input, SharedData sharedData){
		this.input = input;
		this.sharedData = sharedData;
		sem = input.getSemaphoreInstance();
		lastChoice = ClockInput.SHOW_TIME;
		timeSignal = new CountingSem(0);
		alarmSignal = new CountingSem(0);
	}

	
	public void run(){
		

		while (true){
			sem.take();
			sharedData.stopBeep();
			int newChoice = input.getChoice();
			

			switch (newChoice) {
			case ClockInput.SET_ALARM:
				if (lastChoice == ClockInput.SET_TIME){
					int newTime = input.getValue();
					sharedData.setAlarmTime(TimeConverter.convertToLong(newTime));			
				}
				break;
				
			case ClockInput.SET_TIME:
				if (lastChoice == ClockInput.SET_ALARM){
					int newTime = input.getValue();
					sharedData.setClockTime(TimeConverter.convertToLong(newTime));
				}
				break;
				
			case ClockInput.SHOW_TIME:
				if (lastChoice == ClockInput.SET_ALARM){
					int newTime = input.getValue();
					sharedData.setAlarmTime(TimeConverter.convertToLong(newTime));	
				} else if (lastChoice == ClockInput.SET_TIME){
					int newTime = input.getValue();
					sharedData.setClockTime(TimeConverter.convertToLong(newTime));
				}
				
				break;
			default:
				break;
			}
			lastChoice = newChoice;
		}
		
	}

}
